/*
 * @Description: 部门service
 * @Author: Haor
 * @Date: 2022-05-16 14:30:27
 * @LastEditTime: 2022-05-16 22:44:39
 * @LastEditors: Haor
 */
import { Injectable } from "@nestjs/common";
import { InjectRepository } from '@nestjs/typeorm'
import { Repository, Like } from 'typeorm'
import { CreateJobDto, QueryJobDto } from "@dto/job-dto";
import { JobEntity } from "@entities/job.entity";
import { BusinessException, ParamsException } from "@exceptions";
import { isNumber, pageWrap } from "@utils/data";
import { format } from '@utils/date'
import { HttpPageTemplate, HttpResTemplate, HttpResult } from "@libs/http.result";
import { SnowflakeId } from "@libs/snowflake.id";
import * as fs from "fs";
import * as path from 'path';

@Injectable()
export class JobService {
    constructor(
        @InjectRepository(JobEntity)
        private readonly jobRepository: Repository<JobEntity>) {
    }

    /**
     * 查询职位列表
     */
    async queryJobList(queryJobDto: QueryJobDto): Promise<HttpPageTemplate> {
        const where = {
            deleteStatus: 0,
        }
        if (queryJobDto.keyword) where['name'] = Like(`%${queryJobDto.keyword}%`)
        if (isNumber(queryJobDto.enabled)) {
            where['enabled'] = Number(queryJobDto.enabled)
        }

        // 查询列表
        const [list, total ] = await this.jobRepository.findAndCount({
            where: where,
            ...pageWrap(queryJobDto.pageIndex, queryJobDto.pageSize)
        })
        return HttpResult.pageData({ list, total })
    }

    /**
     * 通过职位名称获取职位信息
     * @param {String} jobName
     * @return {Promise}
     */
    async getJobByName(jobName: string): Promise<JobEntity> {
        return this.jobRepository.findOne({
            where: { name: jobName }
        })
    }

    /**
     * 启用禁用职位
     */
    async enableJob(jobId: number): Promise<HttpResTemplate> {
        const job = await this.jobRepository.findOne({
            select: ['name', 'enabled'],
            where: { id: jobId }
        })
        if (!job) throw new BusinessException('职位不存在')
        await this.jobRepository.update({ id: jobId }, { enabled: job.enabled === 0 ? 1 : 0})
        return HttpResult.success()
    }

    /**
     * 创建职位
     * @param createJobDto
     */
    async createJob(createJobDto: CreateJobDto): Promise<HttpResTemplate> {
        const { name } = createJobDto
        const findJob = await this.getJobByName(name) // 检测是否存在
        if (findJob) throw new BusinessException(`职位已存在`)
        const newJob = this.jobRepository.create(createJobDto)
        newJob.id = SnowflakeId.generate()
        newJob.createTime = format(new Date())
        newJob.jobSort = +createJobDto.sort
        const saveRes = await this.jobRepository.save(newJob)
        if (!saveRes) throw new BusinessException('创建失败')
        return HttpResult.success()
    }

    /**
     * 删除职位
     * @param jobId
     */
    async deleteJob(jobId: number|string): Promise<HttpResTemplate> {
        await this.deleteJobById(+jobId)
        return HttpResult.success()
    }

    /**
     * 批量删除职位
     * @param {Array<number>} idList
     */
    async batchDeleteJob(idList: Array<number|string>): Promise<HttpResTemplate> {
        await Promise.all(idList.map(id => this.deleteJobById(id)))
        return HttpResult.success()
    }

    /**
     * 导出职位列表
     */
    exportJob(): any {
        const file = fs.createReadStream(path.join(process.cwd(), 'package.json'));
        return Promise.resolve(file)
    }

    /**
     * 通过id删除职位
     * @param jobId
     */
    private async deleteJobById(jobId) {
        if (isNaN(jobId)) {
            throw new ParamsException()
        }
        const job = await this.jobRepository.findOne({
            select: ['name', 'enabled'],
            where: { id: jobId }
        })
        if (!job) throw new BusinessException('职位不存在')
        return this.jobRepository.update({ id: jobId },{ deleteStatus: 1 })
    }
}
